﻿using System.Text.Json;
using System.Windows;
using TianlalaHSB.Models;
using TianlalaHSB.Utils;

namespace TianlalaHSB.Views;

public partial class MerchantAccountTransferView : Window
{
    public delegate void ChildWindowClosedHandler(object sender, EventArgs e);

    private readonly MerchantAccountRefund _refund;

    public MerchantAccountTransferView(MerchantAccountRefund data)
    {
        InitializeComponent();
        _refund = data;
    }

    public event ChildWindowClosedHandler? ChildWindowClosed;

    public void ShowWindow()
    {
        if (_refund.oppAcctNo != null) InputTextBox.Text = "2230181522310000080000001001";
        ShowDialog(); // Show() 非模态显示 ShowDialog() 模态显示
    }

    private async void OkButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var bankName = InputTextBox.Text.Trim();
            if (string.IsNullOrEmpty(bankName)) throw new Exception("资金账户不能为空");

            // 准备POST请求的数据 
            var postData = new
            {
                headReqSerialNo = HttpUtil.GetHeadReqSerialNo(),
                _refund.serialNo,
                trDate = _refund.transDate?.Replace("-", ""),
                inSubAcctNo = bankName,
                postscript = "提现失败，申请调账。"
            };

            var responseBody = await HttpUtil.Request("03050103B0033", postData);

            var response = JsonSerializer.Deserialize<Response>(responseBody);
            if (response == null) throw new Exception("调账失败");

            if (response.respType == "F") throw new Exception(response.respMsg);

            base.OnClosed(e);
            ChildWindowClosed?.Invoke(this, EventArgs.Empty);

            //DialogResult = true;
            Close();
        }
        catch (Exception ex)
        {
            // 处理异常，例如网络问题或无效的请求等
            MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        //DialogResult = false;
        Close();
    }
}